import urlparse
import logging
import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import google.appengine.ext.webapp.util
import glp.users

class RenderPage(webapp.RequestHandler):
    def get(self):
        {
            '/dynamic/rec-site-nav.html' : self.RenderRecSiteNav
            }[self.request.path]()

    def RenderRecSiteNav(self):
        user = users.get_current_user()
        user_email = user.email() if user else None
        if not user:
            user_state = 'unauthenticated'
        else:
            user = glp.users.GetPendingRegistration(user_email)
            if user:
                user_state = 'unconfirmed'
            else:
                user = glp.users.GetUser(user_email)
                if user:
                    user_state = 'confirmed'
                else:
                    user_state = 'unregistered'
        parent_url = self.request.get('parent')
        parent_bits = urlparse.urlparse(parent_url)
        self.response.out.write(template.render(
                "templates/rec-site-nav.html", {
                    'user_state' : user_state,
                    'user_email' : user_email,
                    'user_name' : '%s %s' % (user.first_name, user.last_name) if user else None,
                    'base_url' : '%s://%s' % (parent_bits.scheme, parent_bits.hostname),
                    'login_url' : '%s://%s/login?next=%s' % (parent_bits.scheme, parent_bits.hostname, parent_url),
                    'register_url' : '%s://%s/register?next=%s' % (parent_bits.scheme, parent_bits.hostname, parent_url),
                    'logout_url' : users.create_logout_url(parent_url)}))

def main():
    # logging.getLogger().setLevel(logging.DEBUG)
    application = webapp.WSGIApplication([
            ('/dynamic/rec-site-nav.html', RenderPage),
            ], debug=True)
    google.appengine.ext.webapp.util.run_wsgi_app(application)


if __name__ == "__main__":
    main()
